<template>
  <div class="animation" :style="dynamicStyle">{{ label }}</div>
</template>

<script>
import TWEEN from "@tweenjs/tween.js";
export default {
  name: "drop-animation",
  props: {
    label: String,
    top: {
      type: Number,
      default: window.innerHeight / 2
    },
    left: {
      type: Number,
      default: () => {
        return 1100 + Math.random() * 1300;
      }
    }
  },
  data() {
    return {
      stopped: false,
      position: {
        x: this.left,
        y: 0,
        opacity: 1
      },
      size: Math.random() * 0.4
    };
  },
  computed: {
    dynamicStyle() {
      return {
        left: this.position.x + "px",
        // top: this.position.y + "px"
        transform: `translate3d(0, ${this.position.y}px, 0) scale(${
          this.position.opacity + this.size
        })`,
        opacity: this.position.opacity
      };
    }
  },
  mounted() {
    setTimeout(() => {
      this.startAnimation();
    }, 1000);
  },
  methods: {
    genRandomY() {
      // return (window.innerHeight * 1) / 3 + ((window.innerHeight * 1) / 3) * Math.random();
      return this.top;
    },
    startAnimation() {
      // const t = null;
      let position = { x: 0.5, y: 0 };
      let enter = new TWEEN.Tween(position);
      enter.to({ y: this.genRandomY(), x: 1 }, Math.random() * 3000 + 2000);
      enter.easing(TWEEN.Easing.Quadratic.InOut);
      enter.onUpdate(() => {
        this.position = {
          x: this.position.x,
          y: position.y,
          opacity: position.x
        };
      });
      enter.onComplete(() => {
        let move = new TWEEN.Tween(position);
        move.to({ y: this.position.y + 100, x: 1 }, 3000);
        move.easing(TWEEN.Easing.Linear.None);
        move.onUpdate(() => {
          this.position = {
            x: this.position.x,
            y: position.y,
            opacity: position.x
          };
        });
        move.onComplete(() => {
          out.start();
        });
        move.start();
      });

      let out = new TWEEN.Tween(position);
      out.to({ y: window.innerHeight, x: 0.6 }, Math.random() * 3000 + 3000);
      out.easing(TWEEN.Easing.Quadratic.InOut);
      out.onUpdate(() => {
        this.position = {
          x: this.position.x,
          y: position.y,
          opacity: position.x
        };
      });
      out.onComplete(() => {
        this.stopped = true;
        this.$emit("complete", this.name);
      });

      // enter.chain(out);
      enter.start();

      let that = this;
      function animate(time) {
        if (!that.stopped) {
          requestAnimationFrame(animate);
          TWEEN.update(time);
        }
      }

      requestAnimationFrame(animate);
    }
  }
};
</script>

<style scoped>
.animation {
  padding: 20px;
  position: absolute;
  color: #fff;
  top: -100px;
  opacity: 1;
  font-size: 2.47vh;
}
</style>
